/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.http;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 上传媒体文件请求执行器，请求的参数是File, 返回的结果是String
 * 
 * @author WuBo (wub1@minshenglife.com)
 *
 */
public class FormFileRequestExecutor implements RequestExecutor<String, File> {


    private String fieldName;
    private Charset charset = Consts.UTF_8;

    public FormFileRequestExecutor(String fieldName, Charset charset) {
        this.fieldName = fieldName;
        this.charset = charset;
    }

    public FormFileRequestExecutor(String fieldName) {
        this(fieldName, Consts.UTF_8);
    }


    @Override
    public String execute(CloseableHttpClient httpclient, String uri, File file)
            throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(uri);
        if (file != null) {
            HttpEntity entity =
                    MultipartEntityBuilder.create()
                            .addBinaryBody(this.fieldName, file).build();
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type",
                    ContentType.MULTIPART_FORM_DATA.toString());
        }
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String responseContent =
                CharsetResponseHandler.HANDLERS.get(charset).handleResponse(
                        response);
        return responseContent;
    }

}
